//
//  NSDate+CLUtility.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2017/4/6.
//  Copyright © 2021年 梁慧聪. All rights reserved.
//

#import "NSDate+CLUtility.h"

static NSDateFormatter * SQLiteDateFormatter = nil;
static NSDateFormatter * SQLiteDateHourMinuteFormatter = nil;

@interface DateModel ()

@property (nonatomic, copy) NSString *dateString;
@property (nonatomic, copy) NSString *hourMinute;

@end

@implementation DateModel

- (instancetype)initWithDate:(NSString *)date hourMinute:(NSString *)hourMinute{
    if (self = [super init]) {
        _dateString = date;
        _hourMinute = hourMinute;
    }
    return self;
}

@end

@implementation NSDate (CLUtility)

+ (DateModel *)currentDateModel{
    NSDate *date = [NSDate date];
    
    DateModel *dateModel = [[DateModel alloc] initWithDate:[SQLiteDateFormatter stringFromDate:date] hourMinute:[SQLiteDateHourMinuteFormatter stringFromDate:date]];
    
    return dateModel;
}

+ (NSString *)currentDate{
    NSDate *date = [NSDate date];
    
    return [SQLiteDateFormatter stringFromDate:date];
}

+ (NSString *)yesterdayDate{
    NSDate *date = [NSDate date];
    
    return [SQLiteDateFormatter stringFromDate:[NSDate dateWithTimeInterval:-24 * 60 * 60 sinceDate:date]];
}

+ (void)initialize{
    if (self == [NSDate class]) {
        SQLiteDateFormatter = [[NSDateFormatter alloc] init];
        [SQLiteDateFormatter setDateFormat:@"yyyy-MM-dd"];
        SQLiteDateHourMinuteFormatter = [[NSDateFormatter alloc] init];
        [SQLiteDateHourMinuteFormatter setDateFormat:@"HH:mm"];
    }
}

/// 获得当前时间戳
+ (NSTimeInterval)timer1970:(BOOL)isMsec {
    if (isMsec) {
        return [[NSDate date] timeIntervalSince1970] * 1000;
    } else {
        return [[NSDate date] timeIntervalSince1970];
    }
}

/// 计算显示时间
+ (NSString *)timerString:(NSInteger)time {
    
    NSInteger currentTime = (NSInteger)[self timer1970:NO];
    
    NSInteger spacing = currentTime - time;
    
    if (spacing < 60) {
        return @"刚刚";
    }else if (spacing < (60 * 60)) {
        return [NSString stringWithFormat:@"%ld分钟前",spacing / 60];
    }else if (spacing < (60 * 60 * 24)) {
        return [NSString stringWithFormat:@"%ld小时前",spacing / 60 / 60];
    }else if (spacing < (60 * 60 * 24 * 4)) {
        return [NSString stringWithFormat:@"%ld天前",spacing / 60 / 60 / 24];
    }else{
        return [SQLiteDateHourMinuteFormatter stringFromDate:[NSDate date]];
    }
}

/// 获取指定时间字符串 (dateFormat: "YYYY-MM-dd-HH-mm-ss")
+ (NSString *)timerStringFormat:(NSString *)dateFormat {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    return [dateFormatter stringFromDate:[NSDate date]];
}
@end
